package com.outsourcing.bottle.ui;

import java.util.HashMap;
import java.util.List;

import oauth.facebook.AsyncFacebookRunner;
import oauth.facebook.BaseRequestListener;
import oauth.facebook.DialogError;
import oauth.facebook.Facebook;
import oauth.facebook.Facebook.DialogListener;
import oauth.facebook.FacebookError;
import oauth.facebook.SessionEvents;
import oauth.facebook.SessionEvents.AuthListener;
import oauth.facebook.Util;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.db.OtherConfigTable;
import com.outsourcing.bottle.db.PlatformAccountTable;
import com.outsourcing.bottle.domain.FriendEntry;
import com.outsourcing.bottle.domain.InitFriendInfo;
import com.outsourcing.bottle.domain.LoginUserInfo;
import com.outsourcing.bottle.domain.LoginUserInfoEntry;
import com.outsourcing.bottle.domain.OtherConfigEntry;
import com.outsourcing.bottle.domain.PlatformAccount;
import com.outsourcing.bottle.domain.PlatformBindConfig;
import com.outsourcing.bottle.domain.ResponseResult;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.oauth.OAuth;
import com.outsourcing.bottle.remoteimage.RemoteImageView;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.widget.ElasticScrollView;
/**
 * 
 * @author 06peng
 *
 */
public class BindInviteActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener {

	private LoginUserInfoEntry entry;
	private final int init_loginuser_info = 1;
	private final int error = 2;
	private final int invite_or_syncfriends = 3;
	private final int cancel_bind = 5;
	private final int cancel_bind_success = 6;
	private final int do_success = 7;
	private final int search_friend = 8;
	
	
	private RelativeLayout twitterLayout;
	private RelativeLayout facebookLayout;
	private RelativeLayout weiboLayout;
	private RelativeLayout tencentLayout;
	private RelativeLayout renrenLayout;
	private RelativeLayout doubanLayout;
	private RelativeLayout qqLayout;
	private ImageView backView;
	private EditText searchEdit;
	
	private ElasticScrollView elasticScrollView;
	private View contentView;
	private LinearLayout bodyLayout;
	private List<FriendEntry> friendList;
	
	private Handler handler;
	private String platform;
	private boolean isGoOAuth;
	private OtherConfigEntry ocEntry;
	public static final String CALLBACKURL = "app:authorize";
	
	private final int oauth_tritter =28;
	private final int oauth_facebook = 29;
	private final int oauth_weibo = 30;
	private final int oauth_tencent = 31;
	private final int oauth_renren = 32;
	private final int oauth_douban = 33;
	private final int oauth_qq = 34;
	private final int oauth_bind = 35;
	
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
	private SessionListener mSessionListener = new SessionListener();
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.bind_invite);
		handler = new Handler(this);
		initWidget();
		initBindUI();
		OtherConfigTable ot = new OtherConfigTable();
		ocEntry = ot.getBottleOtherConfig();
	}
	
	private void initWidget() {
		elasticScrollView = (ElasticScrollView) findViewById(R.id.refresh_view);
		contentView = LayoutInflater.from(this).inflate(R.layout.bind_invite_content, null);
		elasticScrollView.addChild(contentView);
		bodyLayout = (LinearLayout) contentView.findViewById(R.id.bind_invite_bodylayout);
		
		twitterLayout = (RelativeLayout) contentView.findViewById(R.id.bind_invite_twitter_layout);
		twitterLayout.setOnClickListener(this);
		facebookLayout = (RelativeLayout) contentView.findViewById(R.id.bind_invite_facebook_layout);
		facebookLayout.setOnClickListener(this);
		weiboLayout = (RelativeLayout) contentView.findViewById(R.id.bind_invite_weibo_layout);
		weiboLayout.setOnClickListener(this);
		tencentLayout = (RelativeLayout) contentView.findViewById(R.id.bind_invite_tencent_layout);
		tencentLayout.setOnClickListener(this);
		renrenLayout = (RelativeLayout) contentView.findViewById(R.id.bind_invite_renren_layout);
		renrenLayout.setOnClickListener(this);
		doubanLayout = (RelativeLayout) contentView.findViewById(R.id.bind_invite_douban_layout);
		doubanLayout.setOnClickListener(this);
		qqLayout = (RelativeLayout) contentView.findViewById(R.id.bind_invite_qq_layout);
		qqLayout.setOnClickListener(this);
		backView = (ImageView) findViewById(R.id.topbar_back);
		backView.setOnClickListener(this);
		searchEdit = (EditText) contentView.findViewById(R.id.bind_invite_search_edit);
		searchEdit.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (!searchEdit.getText().toString().trim().equals("")) {
					UICore.eventTask(BindInviteActivity.this, BindInviteActivity.this, search_friend, "", null);
				}
				return false;
			}
		});
	}
	
	private void initBindUI() {
		if (entry == null) {
			LoginUserInfoTable userTable = new LoginUserInfoTable();
			entry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
		}
		if (entry != null) {
			if (entry.getTwitterok() == 1) {
				((ImageView) findViewById(R.id.bind_invite_twitter_binded)).setVisibility(View.VISIBLE);
			} else {
				((ImageView) findViewById(R.id.bind_invite_twitter_binded)).setVisibility(View.GONE);
			}
			if (entry.getFacebookok() == 1) {
				((ImageView) findViewById(R.id.bind_invite_facebook_binded)).setVisibility(View.VISIBLE);
			} else {
				((ImageView) findViewById(R.id.bind_invite_facebook_binded)).setVisibility(View.GONE);
			}
			if (entry.getSinaok() == 1) {
				((ImageView) findViewById(R.id.bind_invite_weibo_binded)).setVisibility(View.VISIBLE);
			} else {
				((ImageView) findViewById(R.id.bind_invite_weibo_binded)).setVisibility(View.GONE);
			}
			if (entry.getTqqok() == 1) {
				((ImageView) findViewById(R.id.bind_invite_tencent_binded)).setVisibility(View.VISIBLE);
			} else {
				((ImageView) findViewById(R.id.bind_invite_tencent_binded)).setVisibility(View.GONE);
			}
			if (entry.getRenrenok() == 1) {
				((ImageView) findViewById(R.id.bind_invite_renren_binded)).setVisibility(View.VISIBLE);
			} else {
				((ImageView) findViewById(R.id.bind_invite_renren_binded)).setVisibility(View.GONE);
			}
			if (entry.getDoubanok() == 1) {
				((ImageView) findViewById(R.id.bind_invite_douban_binded)).setVisibility(View.VISIBLE);
			} else {
				((ImageView) findViewById(R.id.bind_invite_douban_binded)).setVisibility(View.GONE);
			}
			if (entry.getQqok() == 1) {
				((ImageView) findViewById(R.id.bind_invite_qq_binded)).setVisibility(View.VISIBLE);
			} else {
				((ImageView) findViewById(R.id.bind_invite_qq_binded)).setVisibility(View.GONE);
			}
		}
	}
	
	@Override
	public void onClick(View v) {
		if (v == twitterLayout) {
			if (ocEntry.getTwitter_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (entry.getTwitterok() == 1) {
				doChoseItemAction(getString(R.string.login_txt_twitter), 5);
			} else {
				UICore.eventTask(this, this, oauth_tritter, "", null);
			}
		} else if (v == facebookLayout) {
			if (ocEntry.getFacebook_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (entry.getFacebookok() == 1) {
				doChoseItemAction(getString(R.string.login_txt_facebook), 6);
			} else {
				isGoOAuth = true;
				platform = PlatformBindConfig.Facebook;
				mFacebook = new Facebook(PlatformBindConfig.Facebook_AppID);
				mAsyncRunner = new AsyncFacebookRunner(mFacebook);
				SessionEvents.addAuthListener(new SampleAuthListener());
				SessionEvents.addAuthListener(mSessionListener);
				mFacebook.authorize((BasicActivity) AppContext.getContext(), new String[] {}, new LoginDialogListener());
			}
		} else if (v == weiboLayout) {
			if (ocEntry.getWeibo_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (entry.getSinaok() == 1) {
				doChoseItemAction(getString(R.string.login_txt_weibo), 1);
			} else {
				UICore.eventTask(this, this, oauth_weibo, "", null);
			}
		} else if (v == tencentLayout) {
			if (ocEntry.getTencent_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (entry.getTqqok() == 1) {
				doChoseItemAction(getString(R.string.login_txt_tencent), 2);
			} else {
				UICore.eventTask(this, this, oauth_tencent, "", null);
			}
		} else if (v == renrenLayout) {
			if (ocEntry.getRenren_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (entry.getRenrenok() == 1) {
				doChoseItemAction(getString(R.string.login_txt_renren), 3);
			} else {
				UICore.eventTask(this, this, oauth_renren, "", null);
			}
		} else if (v == doubanLayout) {
			if (ocEntry.getDouban_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (entry.getDoubanok() == 1) {
				doChoseItemAction(getString(R.string.login_txt_douban), 4);
			} else {
				UICore.eventTask(this, this, oauth_douban, "", null);
			}
		} else if (v == qqLayout) {
			if (ocEntry.getQq_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			if (entry.getQqok() == 1) {
				doChoseItemAction(getString(R.string.login_txt_qq), 0);
			} else {
				UICore.eventTask(this, this, oauth_qq, "", null);
			}
		} else if (v == backView) {
			finish();
		}
	}
	
	private void getLoginUserInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());

		try {
			String result = HttpUtils.doGet(url.toString());
			if (result == null) {
				return;
			}
			Gson gson = new Gson();
			LoginUserInfo loginUserInfo = gson.fromJson(result, LoginUserInfo.class);
			LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable();
			if (null != loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid())) {
				loginUserInfoTable.deleteLoginUserInfoById(AppContext.getInstance().getLogin_uid());
				loginUserInfoTable.saveLoginUserInfo(loginUserInfo
						.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
			} else {
				loginUserInfoTable.saveLoginUserInfo(loginUserInfo
						.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
			}
			entry = loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
			handler.sendEmptyMessage(init_loginuser_info);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	private void syncFirendsOrBind(String url, String openType) {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("open_type", openType);
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
	        	JSONObject object = new JSONObject(result);
	        	JSONObject resultObj = object.getJSONObject("results");
	        	int success = resultObj.getInt("success");
	        	if (success == 0) {
	        		String errmsg = resultObj.getString("errmsg");
	        		Message msg = Message.obtain(handler, error, errmsg);
	        		handler.sendMessage(msg);
	        	} else {
	        		String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, do_success, successmsg);
					handler.sendMessage(msg);
	        	}
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void cancelBind(String openType) {
		String url = UrlConfig.open_unbind;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("open_type", openType);
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
	        	JSONObject object = new JSONObject(result);
	        	JSONObject resultObj = object.getJSONObject("results");
	        	int success = resultObj.getInt("success");
	        	if (success == 0) {
	        		String errmsg = resultObj.getString("errmsg");
	        		Message msg = Message.obtain(handler, error, errmsg);
	        		handler.sendMessage(msg);
	        	} else {
	        		String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, cancel_bind_success, successmsg);
					handler.sendMessage(msg);
	        	}
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void search() {
		StringBuffer url = new StringBuffer(UrlConfig.search_users_list);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&keyword=" + searchEdit.getText().toString().trim());
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result != null) {
				Gson gson = new Gson();
				InitFriendInfo info = gson.fromJson(result, InitFriendInfo.class);
				ResponseResult res = info.getResults();
				if (res.getAuthok() == 1) {
					friendList = info.getUsers_list();
				}
				handler.sendEmptyMessage(search_friend);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case init_loginuser_info:
			initBindUI();
			break;
		case error:
			onToast((String) msg.obj);
			break;
		case do_success:
			onToast((String) msg.obj);
			break;
		case cancel_bind_success:
			onToast((String) msg.obj);
			UICore.eventTask(this, this, init_loginuser_info, "get_logininfo", null);
			break;
		case oauth_facebook:
			PlatformAccount account = (PlatformAccount) msg.obj;
			UICore.eventTask(BindInviteActivity.this, BindInviteActivity.this, oauth_facebook, "", account);
			break;
		case oauth_bind:
			UICore.eventTask(this, this, init_loginuser_info, "get_logininfo", null);
			break;
		case search_friend:
			bodyLayout.removeAllViews();
			if (friendList != null && !friendList.isEmpty()) {
				for (FriendEntry entry : friendList) {
					FriendView view = new FriendView(this, entry);
					bodyLayout.addView(view);
				}
			}
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (isGoOAuth) {
			AppContext.getInstance().setOAUTH_TYPE(-1);
			isGoOAuth = false;
			UICore.eventTask(this, this, init_loginuser_info, "get_logininfo", null);
		}
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case init_loginuser_info:
			getLoginUserInfo();
			break;
		case invite_or_syncfriends:
			String[] params = (String[]) obj;
			syncFirendsOrBind(params[0], params[1]);
			break;
		case cancel_bind:
			cancelBind((String)obj);
			break;
		case oauth_douban:
			isGoOAuth = true;
			platform = PlatformBindConfig.Douban;
			OAuth oauth = new OAuth(this, handler, platform, PlatformBindConfig.Douban_AppKey,
					PlatformBindConfig.Douban_AppSecret);
			oauth.requestAccessToken(CALLBACKURL, PlatformBindConfig.Douban_Request_Token,
					PlatformBindConfig.Douban_Access_Token, PlatformBindConfig.Douban_Authorize);
			break;
		case oauth_facebook:
			PlatformAccount account = (PlatformAccount) obj;
			checkBind(account);
			break;
		case oauth_qq:
			isGoOAuth = true;
			platform = PlatformBindConfig.QQ;
			OAuth oauth2 = new OAuth(this, handler, platform);
			oauth2.requestAccessTokenForOAuth2(PlatformBindConfig.QQ_Authorize);
			break;
		case oauth_renren:
			platform = PlatformBindConfig.Renren;
			OAuth oauth3 = new OAuth(this, handler, platform);
			oauth3.requestAccessTokenForOAuth2(PlatformBindConfig.Renren_Authorize);
			break;
		case oauth_tencent:
			isGoOAuth = true;
			platform = PlatformBindConfig.Tencent;
			OAuth oauth4 = new OAuth(this, handler, platform);
			oauth4.requestAccessTokenForOAuth2(PlatformBindConfig.Tencent_Authorize_2);
			break;
		case oauth_tritter:
			isGoOAuth = true;
			platform = PlatformBindConfig.Twitter;
			OAuth oauth5 = new OAuth(this, handler, PlatformBindConfig.Twitter,
					PlatformBindConfig.Twitter_ConsumerKey, PlatformBindConfig.Twitter_ConsumerSecret);
			oauth5.requestAcccessTokenForTwitter();
			break;
		case oauth_weibo:
			isGoOAuth = true;
			platform = PlatformBindConfig.Sina;
			OAuth oauth6 = new OAuth(this, handler, platform);
			oauth6.requestAccessTokenForOAuth2(PlatformBindConfig.Sina_Authorize2);
			break;
		case search_friend:
			search();
			break;
		default:
			break;
		}
	}
	
	private void doChoseItemAction(String bind, final int openType) {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		String[] choices;
		choices = new String[3];
		choices[0] = getString(R.string.bind_invate_send_invate); 
		choices[1] = getString(R.string.bind_invate_sync_friends); 
		String cancelBind = null;
		if (AppContext.language == 1) {
			cancelBind = bind + "绑定";
		} else {
			cancelBind = bind;
		}
		choices[2] = getString(R.string.bind_invate_cancel_bind) + cancelBind; 
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							String[] params = new String[]{ UrlConfig.open_invite, String.valueOf(openType) };
							UICore.eventTask(BindInviteActivity.this, BindInviteActivity.this, invite_or_syncfriends, "open_invite", params);
							break;
						case 1:
							String[] params2 = new String[]{ UrlConfig.open_syncfriends, String.valueOf(openType) };
							UICore.eventTask(BindInviteActivity.this, BindInviteActivity.this, invite_or_syncfriends, "syncfriends", params2);
							break;
						case 2:
							UICore.eventTask(BindInviteActivity.this, BindInviteActivity.this, cancel_bind, "cancel_bind", String.valueOf(openType));
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			if (OAuth.reciver != null) {
				unregisterReceiver(OAuth.reciver);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class SampleAuthListener implements AuthListener {

		public void onAuthSucceed() {
			System.out.println("You have logged in! ");
		}

		public void onAuthFail(String error) {
			System.out.println("Login Failed: " + error);
		}
	}

	public class SampleRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {
				PlatformAccount account = new PlatformAccount();
				Log.d("Facebook-Example", "Response: " + response.toString());
				JSONObject json = Util.parseJson(response);
				account.setAccessToken(mFacebook.getAccessToken());
				if (json.has("name")) {
					account.setNickName(json.getString("name"));
				}
				account.setOpenAvatar("https://graph.facebook.com/"+json.getString("id")+"/picture?type=large");
				account.setOpenExpire(String.valueOf(mFacebook.getAccessExpires()));
				account.setOpenType(6);
				account.setOpenUid(json.getString("id"));
				PlatformAccountTable paTable = new PlatformAccountTable();
				paTable.save(account);
				if (account.getOpenUid() != null && !account.getOpenUid().equals("")) {
					Message msg = Message.obtain(handler, oauth_facebook, account);
					handler.sendMessage(msg);
				}
			} catch (JSONException e) {
				Log.w("Facebook-Example", "JSON Error in response");
			} catch (FacebookError e) {
				Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
			}
		}
	}

	private final class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            SessionEvents.onLoginSuccess();
        }

        public void onFacebookError(FacebookError error) {
            SessionEvents.onLoginError(error.getMessage());
        }
        
        public void onError(DialogError error) {
            SessionEvents.onLoginError(error.getMessage());
        }

        public void onCancel() {
            SessionEvents.onLoginError("Action Canceled");
        }
    }
	
	private class SessionListener implements AuthListener {
        
        public void onAuthSucceed() {
            mAsyncRunner.request("me", new SampleRequestListener());
        }
        
        public void onAuthFail(String error) {
        	
        }
    }
	
	private void checkBind(PlatformAccount account) {
		String url = UrlConfig.check_bind;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("open_type", String.valueOf(account.getOpenType()));
		paramsMap.put("access_token", account.getAccessToken());
		paramsMap.put("token_secret", account.getTokenSecret());
		paramsMap.put("nickname", account.getNickName());
		paramsMap.put("open_uid", account.getOpenUid());
		paramsMap.put("open_sex", String.valueOf(account.getOpenSex()));
		paramsMap.put("open_expire", account.getOpenExpire());
		paramsMap.put("open_avatar", account.getOpenAvatar());
		paramsMap.put("device_token", AppContext.getInstance().getDeviceId());
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			JSONObject object = new JSONObject(result);
			if (object.has("results")) {
				final JSONObject resultObj = object.getJSONObject("results");
				System.out.println(resultObj);
				int isbind = resultObj.getInt("isbind");
				if (AppContext.getInstance().getLogin_uid() != 0 &&  AppContext.getInstance().getLogin_token() != null) {
					if (isbind == 1) {
						if (account.getOpenType() > 0) {
							AppContext.getInstance().setOAUTH_TYPE(account.getOpenType());
							handler.sendEmptyMessage(oauth_bind);
						} else {
							AppContext.getInstance().setOAUTH_TYPE(-1);
						}
					} 
				} 
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	public class FriendView extends LinearLayout {
		
		private View convertView;
		private FriendEntry entry;
		
		public FriendView(Context context, FriendEntry entry) {
			super(context);
			this.entry = entry;
			initWidget();
			setOrientation(LinearLayout.VERTICAL);
			addView(convertView);
			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			params.topMargin = 5;
			ImageView image = new ImageView(context);
			image.setBackgroundResource(R.drawable.line_gray);
			addView(image);
		}

		public FriendView(Context context, AttributeSet attrs) {
			super(context, attrs);
		}
		
		private void initWidget() {
			try {
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.user_space_header, null);
				RemoteImageView avatarView = (RemoteImageView) convertView.findViewById(R.id.user_space_avatar);
				TextView nicknameView = (TextView) convertView.findViewById(R.id.user_space_nickname);
				TextView memoView = (TextView) convertView.findViewById(R.id.user_space_memo);
				ImageView sexView = (ImageView) convertView.findViewById(R.id.user_space_sex);
				TextView doingView = (TextView) convertView.findViewById(R.id.user_space_doing);
				TextView addressView = (TextView) convertView.findViewById(R.id.user_space_address);
				
				nicknameView.setText(entry.getNickname());
				if (entry.getSex() == 1) {
					sexView.setBackgroundResource(R.drawable.male);
				} else if (entry.getSex() == 2) {
					sexView.setBackgroundResource(R.drawable.female);
				}
				if (TextUtil.notEmpty(entry.getMemo())) {
					((TextView) convertView.findViewById(R.id.user_space_memo)).setVisibility(View.VISIBLE);
					memoView.setText("-" + entry.getMemo());
				} else {
					((TextView) convertView.findViewById(R.id.user_space_memo)).setVisibility(View.GONE);
					memoView.setVisibility(View.GONE);
				}
				if (TextUtil.notEmpty(entry.getCity()) &&  TextUtil.notEmpty(entry.getCountry())) {
					addressView.setVisibility(View.VISIBLE);
					if (AppContext.language == 1) {
						addressView.setText(getString(R.string.user_from) + entry.getCountry() + " " + entry.getCity());
					} else {
						addressView.setText(getString(R.string.user_from) + entry.getCity() + " " + entry.getCountry());
					}
				} else {
					addressView.setVisibility(View.GONE);
				}
				String html = "<font color=black>"+getString(R.string.user_info_doing)+"</font>";
				doingView.setText(Html.fromHtml(html + entry.getDoing()));
				avatarView.setDefaultImage(R.drawable.avatar_default_big);
				avatarView.setImagePath(entry.getAvatar());
				avatarView.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(BindInviteActivity.this, UserSpaceActivity.class);
						intent.putExtra("ouid", entry.getUid());
						startActivity(intent);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
}
